#!/opt/chef/embedded/bin/ruby


# This script can be used to push your key file and the bootstrapchefuser.sh to the /tmp dir 
# on the host where you want to run chef-client.  The script assumes you have root password.

# When you run it, you will be prompted repeatedly to give root password three times for each host in 
# your deployment file.Once for key,  once for script and once to execute the script.

require 'optparse'
require 'json'
require 'erubis'

`which sshpass`
if ( $? != 0 ) 
	puts "This program requires you to install sshpass to run it"
	exit -127
end

dname = ARGV[0]
keyfileloc = ARGV[1]
userid="idcuser"
groupid="idcgroup"
if ( ARGV[2] != nil )
	userid=ARGV[2]
end
if ( ARGV[3] != nil )
	groupid=ARGV[3]
end


def usage(exitcode)
    puts "Usage:  scripts/pushchefuser.rb <deployment-name> <public-key-file> [userid] [groupid]"
	puts "  this script can be used to configure the chef-power-user on all the severs in a deployment file"
	puts "  the script assumes a Unix or Linux OS and sshpass must be installed.  Root password is required."
    exit exitcode
end

if ( dname == nil  )
    puts "Please provide a deployment name."
    usage(1)
end

if ( keyfileloc == nil  )
    puts "Please provide keyfile location."
    usage(2)
end

if ( ! File.file?("deployments/conf/#{dname}.json"))
    puts "Deployment file does not exist ./deployments/conf/#{dname}.json"
    usage(4)
end

if ( ! File.file?("#{keyfileloc}"))
    puts "Key file #{keyfileloc} does not exist"
    usage(5)
end

input = File.read('nodes/nodetemplate.json')
eruby = Erubis::Eruby.new(input)
json = File.read("deployments/conf/#{dname}.json")
depl = JSON.parse(json)

print "What is the root password?"
$stdout.flush
rootpassword = STDIN.gets.chomp

id = 0
threads = []
depl['nodes'].each() do |node|
    cmdstr = "sshpass -p \'#{rootpassword}\' scp ./scripts/bootstrapchefuser.sh root@#{node["ip"]}:/tmp"
    puts "Executing command: " + cmdstr
    output =  `#{cmdstr}`
    puts output
    if $? != 0
      node[:error] = true
    end
    cmdstr = "sshpass -p \'#{rootpassword}\' scp #{keyfileloc} root@#{node["ip"]}:/tmp"
    puts "Executing command: " + cmdstr
    output =  `#{cmdstr}`
    puts output
    if $? != 0
      node[:error] = true
    end
	`sshpass -p \'#{rootpassword}\' ssh -l root #{node["ip"]} sh /tmp/bootstrapchefuser.sh /tmp/#{keyfileloc} #{userid} #{groupid}`
end



